package lego.diagram.edit.parts.custom;

import java.util.List;

import lego.diagram.edit.parts.ActionerPortEditPart;
import lego.diagram.edit.parts.SensorPortEditPart;
import lego.diagram.edit.parts.custom.figure.BrikFigure;

import org.eclipse.draw2d.FigureListener;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.editparts.AbstractEditPart;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ListCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure;
import org.eclipse.gmf.runtime.gef.ui.internal.figures.CircleFigure;

public class BrikCompartmentFigureListener implements FigureListener {

	private ListCompartmentEditPart compartmentEditPart = null;
	private BrikFigure brikFigure;

	public static final double R = 50; // The base length
	public static final double REF_H = R * 6; // Reference height

	public BrikCompartmentFigureListener(
			ListCompartmentEditPart compartmentEditPart, BrikFigure brikFigure) {
		this.compartmentEditPart = compartmentEditPart;
		this.brikFigure = brikFigure;
	}

	@Override
	public void figureMoved(IFigure f) {
		ResizableCompartmentFigure figure = (ResizableCompartmentFigure) f;
		if (figure.getSize().width != 0) {
			IFigure contentPane = figure.getContentPane();
			Insets is = figure.getInsets();

			// Set the constraints (bounds) for the rounded rectangle
			Rectangle constraint = new Rectangle(0, (int) ((R / 6)),
					(int) (R * 4), (int) (R * 6));
			contentPane.setConstraint(brikFigure, constraint);

			// Set the constraints for the components
			List<AbstractEditPart> childs = compartmentEditPart.getChildren();
			int actionerPortIndex = 0;
			int sensorPortIndex = 0;
			for (AbstractEditPart child : childs) {
				if (child instanceof AbstractGraphicalEditPart) {
					AbstractGraphicalEditPart gEditPart = (AbstractGraphicalEditPart) child;
					// ActionnerPort
					if (gEditPart instanceof ActionerPortEditPart) {
						int startingPoint = (int) ((R * 3 / 4 + ((R * 3 / 4) * actionerPortIndex)));
						constraint = new Rectangle((int) (startingPoint),
								(int) (0), (int) (R / 3), (int) (R / 2));
						contentPane.setConstraint(gEditPart.getFigure(),
								constraint);
						actionerPortIndex++;
					}
					// SensorPort
					else if (gEditPart instanceof SensorPortEditPart) {
						int startingPointY = (int) ((REF_H - R) + (R / 10 * sensorPortIndex));
						int startingPointX = (int) (R / 3 + ((R * 3 / 4) * sensorPortIndex));
						constraint = new Rectangle(startingPointX,
								startingPointY, (int) (R / 2),
								(int) (R * 3 / 4));
						contentPane.setConstraint(gEditPart.getFigure(),
								constraint);
						sensorPortIndex++;
					}
				}
			}
		}
	}

}
